$(function () {

    var playerRedAnimation = {
        move: new engine.animation({
            url: "images/redPlayer.png",
            numberOfFrames: 1,
            rate: 200,
            width: 34,
        }),
        stand: new engine.animation({
            url: "images/redPlayer.png",
            numberOfFrames: 1,
            rate: 200,
            width: 34,
        })
    };

    var playerBlueAnimation = {
        move: new engine.animation({
            url: "images/bluePlayer.png",
            numberOfFrames: 1,
            rate: 200,
            width: 34,
        }),
        stand: new engine.animation({
            url: "images/bluePlayer.png",
            numberOfFrames: 1,
            rate: 200,
            width: 34,
        })
    };
    
    var bulletAnimation = new engine.animation({
        url: "images/bullet.png",
        numberOfFrames: 1,
        rate: 200,
        width: 7,
    })

    var container, sideBoard, pool;
    var player1, player2;
    var bulletPositions = [];
    var bullets = [];
    var bulletsToRemove = [];

    $("#startButton").click(function () {
        engine.startGame(initialize);
    });

    var initialize = function () {
        $("#myGame").append("<div id='container' style='display: none; width: 600px; height: 600px; background-color: black; position: relative; color: white'>");
        //$("#myGame").append("<img id='backGround' src='images/border.png'; width: 680px; height: 480px; position: absolute;'>");

        $("#myGame").append("<div id='sideBoard' style='display: block; width: 600px; height: 20px; background-color: black; color: white'>");

        $("#myGame").append("<div id='goodText' style='display: block; width: 600px; height: 20px; background-color: black; color: white'>");

        container = $("#container");
        sideBoard = $("#sideBoard");
        goodText = $("#goodText");
        goodText.css("text-align","right");
        goodText.text("Press Space to Pause...");

        container.append("<img id='backGround' src='images/border.png'; width= '600'; height= '600'; position: relative;'>");
        pool = $("#backGround");

        player1 = engine.addSprite(container, "player-tank", { x: 260, y: 300, width: 25, height: 25 });
        player2 = engine.addSprite(container, "player-tank", { x: 300, y: 300, width: 25, height: 25 });

        player1.css("z-index","200");
        player2.css("z-index","200");

        engine.setAnimation(player1, playerBlueAnimation.stand);
        engine.setAnimation(player2, playerRedAnimation.stand);

        engine.addCallback(gameLoop, 1000);
        engine.addCallback(userInput, 100);

        $("#startButton").remove();
        container.css("display", "block");
    }



    var tournCount = 0;
    var pause = false;
    var gameLoop = function () {
        if (!pause) {
            processGameInfo(tournCount);
            tournCount++;
        }
    }

    var userInput = function () {
        //player shoots
        if (engine.keyboard[32]) {
            console.log("pause");
            pause = !pause;
        }
    }

    var processGameInfo = function(tournCount) {
        if (tournCount == gameInfo.length) {
            engine.removeCallback(gameLoop);
            endGame(gameInfo[tournCount - 1].blueAlive);
            return;
        }

        var tournInfo = gameInfo[tournCount];
        sideBoard.text(gameInfo[tournCount].size);

        processBullets(tournInfo);
        
        setPlayerPos(player1, tournInfo.player1);
        setPlayerPos(player2, tournInfo.player2);

        updategameField();
    }

    var setPlayerPos = function(player, positions) {
        var newPositions = getNewPos(positions[0] - 3.5, positions[1] + 3.5);
        //console.log("moving " + object + " " + newPositions);
        player.animate({top: newPositions[1] + "px", left: newPositions[0] + "px"}, 1000);
    }

    var getNewPos = function(posX, posY) {
        var newPos = [];
        newPos.push( (posX + 100)*3);
        newPos.push((100 - posY)*3);

        return newPos;
    }

    var processBullets = function(tournInfo) {
        //Remove dead bullets
        for (var i = 0; i < bulletsToRemove.length; i++) {
            engine.removeAnimation(bulletsToRemove[i]);
            bulletsToRemove[i].remove();
        };
        bulletsToRemove = [];

        //Create and move old Bullets
        var newBullet;
        for (var i = 0; i < bulletPositions.length; i++) {
            newBullet = engine.addSprite(container, "bullet_" + tournInfo.size + "_" + i, 
                { x:bulletPositions[i][0][0], y:bulletPositions[i][0][1], width: 7, height: 7 });

            newBullet.nextPos = bulletPositions[i][1];
            engine.setAnimation(newBullet, bulletAnimation);
            newBullet.animate({top: newBullet.nextPos[1] + "px", left: newBullet.nextPos[0] + "px"}, 1000);
            bulletsToRemove.push(newBullet);
        };

        //Add new bullets
        bulletPositions = [];

        var newPos;
        var nextPos;
        for (var i = 0; i < tournInfo.bullets.length; i++) {
            newPos = getNewPos(tournInfo.bullets[i][0], tournInfo.bullets[i][1]);
            nextPos = getNewPos(tournInfo.bullets[i][2], tournInfo.bullets[i][3]);
            //console.log(newPos + " " + nextPos);
            bulletPositions.push([newPos, nextPos]);

        };
    }

    var updategameField = function() {
        pool.animate({margin: "+=3px", width: "-=6px", height: "-=6px"}, 200);
    }

    var endGame = function (blueAlive) {
        console.log("end : " + blueAlive);
        var endText;
        if (blueAlive) {
            endText = "Blue wins";
        } else {
            endText = "Red wins";
        }

        //$("#endGame").text(endText);
        container.css("font-size", "40px");
        container.css("text-align", "center");
        container.html(endText);

        sideBoard.text("End turn: " + (100 - sideBoard.text()));
        goodText.text(" ");
    }
})